//
//  DemandCollectionCell.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/9.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "DemandCollectionCell.h"
#import "DemandCell.h"
#import "ReleaseModel.h"
#import "HomeModel.h"
@interface DemandCollectionCell()<UITableViewDelegate,UITableViewDataSource,DemandCellDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) NSMutableArray *dataMuta;
@property(nonatomic,assign) NSInteger pageNum;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,strong) ReleaseModel *modelAss;
@property(nonatomic,strong) ReleaseModel *modelAssub;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) MJRefreshNormalHeader *header;
@property(nonatomic,strong) NSMutableArray *titles;
@property(nonatomic,strong) NSMutableArray *subTitles;
@property(nonatomic,strong) NSString *uids;
@property(nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) UIButton *checkBtn;
@property(nonatomic,assign) NSInteger changeInternet;
@end
static NSString *identifierNeed = @"DemandCell";
@implementation DemandCollectionCell

-(NSMutableArray *)dataMuta
{
    if (!_dataMuta) {
        _dataMuta = [NSMutableArray array];
    }
    return _dataMuta;
}
-(NSMutableArray *)titles
{
    if (!_titles) {
        _titles = [NSMutableArray array];
    }
    return _titles;
}
-(NSMutableArray *)subTitles
{
    if (!_subTitles) {
        _subTitles = [NSMutableArray array];
    }
    return _subTitles;
}
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, kWidth, kHeight-40-40) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.contentView.backgroundColor = kWhite;
        self.manager = [AFHTTPSessionManager manager];
//        self.uids = [NSString stringWithFormat:@"%ld",[UserDefaultsHelper readUid]];
        self.modelAss = [[ReleaseModel alloc]init];
        self.modelAssub = [[ReleaseModel alloc]init];
        self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        [self.tableView registerNib:[UINib nibWithNibName:@"DemandCell" bundle:nil] forCellReuseIdentifier:identifierNeed];
        self.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
        self.tableView.mj_header = self.header;
        [self.tableView registerNib:[UINib nibWithNibName:@"DemandCell" bundle:nil] forCellReuseIdentifier:identifierNeed];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(collectDemandContent:) name:@"collectDemandContent" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logIn:) name:@"logIn" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logInOut:) name:@"logInOut" object:nil];
        [self.contentView addSubview:self.tableView];
//        self.pageNum = 1;
        self.pageSize = 10;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeInternet:) name:@"changeInternet" object:nil];
        
    }
    return self;
}
-(void)changeInternet:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"DemandCollectionCell:%@",dict);
}
//-(void)qingqiusibai:(NSNotification *)info
//{
//    XLog(@"DemandCollectionCellqingqiusibai");
//}
- (void)setReleaseModel:(ReleaseModel *)releaseModel
{
    _releaseModel = releaseModel;
    XLog(@"releaseModel:%@",releaseModel.content);
    XLog(@"releaseSubModel:%@",self.releaseSubModel.content);
    self.titles = nil;
    self.subTitles = nil;
    self.dataMuta = nil;
    self.pageNum = 1;
//    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
//    [WSProgressHUD show];
    [self reloadInternetData];
//    [self.header beginRefreshing];
}
#pragma mark-代理:点击子标签
- (void)setReleaseSubModel:(ReleaseModel *)releaseSubModel
{
    _releaseSubModel = releaseSubModel;
    self.dataMuta = nil;
    self.pageNum = 1;
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    self.urlString = [NSString stringWithFormat:@"%@/demand/selectTranslateDemand",kUrl];
    NSString *pageNums = [NSString stringWithFormat:@"%ld",(long)self.pageNum];
    NSString *pageSizes = [NSString stringWithFormat:@"%ld",(long)self.pageSize];
    XLog(@"self.uids:%@",self.uids);
    if ([releaseSubModel.content containsString:@"全部"]) {
        releaseSubModel.content = @"";
    }
    self.dict = @{
                  @"pageNum":pageNums,
                  @"pageSize":pageSizes,
                  @"ass":self.releaseModel.content,
                  @"assub":releaseSubModel.content,
                  @"uid":self.uids
                  };
    XLog(@"self.dict:%@",self.dict);
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *date = [responseObject objectForKey:@"date"];
        XLog(@"date:%@",date);
//        NSInteger empty = [EmptyModel stringIsNullOrEmpty:date];
        if (date.count) {
            for (NSDictionary *dict in date) {
                HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                [self.dataMuta addObject:model];
            }
            if (date.count < 10) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            }else {
                [self.tableView.mj_footer endRefreshing];
            }
        }else {
            self.tableView.emptyDataSetSource = self;
            self.tableView.emptyDataSetDelegate = self;
        }
        if (self.dataMuta.count) {
            MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
            self.tableView.mj_footer = footer;
                [footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
 forState:MJRefreshStateNoMoreData];
                footer.stateLabel.font = [UIFont systemFontOfSize:12];
                footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
            if (!date.count) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            }
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [WSProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XLog(@"error:%@",error);
        [WSProgressHUD dismiss];
    }];
}
-(void)reloadData
{
    [self.tableView reloadData];
}
-(void)refresh
{
    self.dataMuta = nil;
    self.pageNum = 1;
    [self reloadInternetData];
    
}
-(void)reloadMore
{
    self.pageNum ++;
    
    [self reloadInternetMoreData];
    
}
#pragma mark-需求内容
-(void)reloadInternetMoreData
{
    
    
    self.urlString = [NSString stringWithFormat:@"%@/demand/selectTranslateDemand",kUrl];
    NSString *pageNums = [NSString stringWithFormat:@"%ld",(long)self.pageNum];
    NSString *pageSizes = [NSString stringWithFormat:@"%ld",(long)self.pageSize];
    NSInteger empty = [EmptyModel stringIsNullOrEmpty:self.releaseSubModel];
    if (empty !=1) {
        
        self.modelAssub = self.releaseSubModel;
    }else {
        self.modelAssub = self.subTitles[0];
    }
    self.dict = @{
                  @"pageNum":pageNums,
                  @"pageSize":pageSizes,
                  @"ass":self.releaseModel.content,
                  @"assub":self.modelAssub.content,
                  @"uid":[UserDefaultsHelper readUid],
                  @"token":[UserDefaultsHelper readToken]
                  };
    XLog(@"self.dict:%@",self.dict);
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *date = [responseObject objectForKey:@"date"];
        
        XLog(@"date:%@",date);
        if (date.count) {
            for (NSDictionary *dict in date) {
                HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                [self.dataMuta addObject:model];
            }
            if (date.count < 10) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            }else {
                [self.tableView.mj_footer endRefreshing];
            }
        }else {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [WSProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WSProgressHUD dismiss];
        XLog(@"error:%@",error);
    }];

}
-(void)reloadInternetData
{
//    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
//    [WSProgressHUD show];
    //使用GCD的信号量 dispatch_semaphore_t 创建同步请求
    dispatch_group_t group =dispatch_group_create();
    dispatch_queue_t globalQueue=dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    dispatch_group_async(group, globalQueue, ^{
        for (int i = 0; i<2; i++) {
            if (i == 0) {
                self.urlString =[NSString stringWithFormat:@"%@/associationTypeSub/listByFatherId",kUrl];
                NSString *fatherId = [NSString stringWithFormat:@"%ld",self.releaseModel.id];
                self.dict = @{
                              @"fatherId":fatherId
                              };
            }else {
                self.urlString = [NSString stringWithFormat:@"%@/demand/selectTranslateDemand",kUrl];
                NSString *pageNums = [NSString stringWithFormat:@"%ld",(long)self.pageNum];
                NSString *pageSizes = [NSString stringWithFormat:@"%ld",(long)self.pageSize];
//                self.modelAss = self.titles[self.releaseModel.id-1];
                NSInteger empty = [EmptyModel stringIsNullOrEmpty:self.releaseSubModel];
                if (empty !=1) {
                    
                    self.modelAssub = self.releaseSubModel;
                }else {
                    self.modelAssub = self.subTitles[0];
                }
                self.dict = @{
                              @"pageNum":pageNums,
                              @"pageSize":pageSizes,
                              @"ass":self.releaseModel.content,
                              @"assub":self.modelAssub.content,
                              @"uid":[UserDefaultsHelper readUid],
                              @"token":[UserDefaultsHelper readToken]
                              };
                XLog(@"self.dict:%@",self.dict);
            }
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSArray *date = [responseObject objectForKey:@"date"];
                if (i == 0) {
                    for (NSDictionary *dict in date) {
                        self.modelAssub = [ReleaseModel mj_objectWithKeyValues:dict];
                        [self.subTitles addObject:self.modelAssub];
                    }
                }else {
                    XLog(@"date.count:%ld",date.count);
                     if (date.count) {
                         for (NSDictionary *dict in date) {
                             HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                             [self.dataMuta addObject:model];
                         }
                         if (!self.dataMuta.count){
                             self.tableView.emptyDataSetSource = self;
                             self.tableView.emptyDataSetDelegate = self;
                         }else {
                             MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
                             self.tableView.mj_footer = footer;
                             [footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
 forState:MJRefreshStateNoMoreData];
                             footer.stateLabel.font = [UIFont systemFontOfSize:12];
                             footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
                             
                         }
                         if (date.count < 10) {
                             self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                         }else {
                             [self.tableView.mj_footer endRefreshing];
                         }
                     }else {
                     }
                }
                dispatch_semaphore_signal(semaphore);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                XLog(@"error:%@",error);
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
        
    });
    
    dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
        XLog(@"DemandCollection%@---全部结束。。。",[NSThread currentThread]);
        [WSProgressHUD dismiss];
        if (!self.dataMuta.count) {
            self.tableView.emptyDataSetSource = self;
            self.tableView.emptyDataSetDelegate = self;            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        });
    });
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataMuta.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    DemandCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierNeed forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    HomeModel *model = self.dataMuta[indexPath.row];
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.homeModel = model;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   return 144;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HomeModel *model = self.dataMuta[indexPath.row];
    if ([self.delegate respondsToSelector:@selector(demandCollectionCell:withModel:withIndexPath:)]) {
        [self.delegate demandCollectionCell:self withModel:model withIndexPath:indexPath];
    }
}
#pragma mark-代理:显示联系人
-(void)demandCell:(DemandCell *)demandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                
                HomeModel *model = self.dataMuta[indexPath.row];
                model.show = clickBtn.selected;
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
    

}
#pragma mark-代理:搜藏后刷新
-(void)collectDemandContent:(NSNotification *)info
{
    [self refresh];
}
-(void)logIn:(NSNotification *)info
{
    [self refresh];
}
-(void)logInOut:(NSNotification *)info
{
    [self refresh];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
#pragma mark-代理:收藏
- (void)demandCell:(DemandCell *)demandCell withCollectBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else{
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                clickBtn.selected = !clickBtn.selected;
                if (clickBtn.selected) {
                    homeModel.collectStatus = 1;
                }else {
                    homeModel.collectStatus = 0;
                }
                NSString *ids = [NSString stringWithFormat:@"%ld",homeModel.id];
                NSString *status = [NSString stringWithFormat:@"%d",clickBtn.selected];
                homeModel.collectStatus = clickBtn.selected;
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"id":ids,
                              @"type":@"1",
                              @"status":status,
                              @"token":[UserDefaultsHelper readToken]
                              };
                XLog(@"DemandCollectionCellself.dict:%@",self.dict);
                [CustomeManager POSTWithURLIndex:34 parameters:self.dict success:^(NSDictionary *dict) {
                    NSString *status = [dict objectForKey:@"status"];
                    if ([status integerValue] == 200) {
                        if ([self.delegate respondsToSelector:@selector(demandCollectionCell:withCollectReload:)]) {
                            [self.delegate demandCollectionCell:self withCollectReload:YES];
                        }
                    }
                } failure:^(NSError *error) {
                }];
                
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
@end
